package org.study.solr.boot.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 参考 https://blog.csdn.net/qq_31254489/article/details/121419352
 *
 * @author Administrator
 * @date 2022-09-27
 */
public class ParameterizedTypeUtils {
    /**
     * 根据索引获取泛型实例类。相关 Api：
     * 1、带泛型的属性值 Field.getGenericType
     * 2、带泛型的方法返回值 Method.getGenericReturnType
     * 3、带泛型的父类 Class.getGenericSuperclass
     * 4、带泛型的接口集合 Class.getGenericInterfaces
     *
     * @param type  类型
     * @param index
     * @return java.lang.reflect.Type
     */
    public static Type get(Type type, int index) {
        ParameterizedType clazz = (ParameterizedType) type;
        Type[] actualTypes = clazz.getActualTypeArguments();
        return actualTypes[index];
    }

    /*static class TypeTest {
        List<Integer> list1 = new ArrayList<>();
        List<Integer[]> list2 = new ArrayList<>();
        List<List<Integer>> list3 = new ArrayList<>();

        List<String> test() {
            return null;
        }

        List<Map<String, Object>> testMap() {
            return null;
        }

        public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
            Type list1 = TypeTest.class.getDeclaredField("list1").getGenericType();
            Type list2 = TypeTest.class.getDeclaredField("list2").getGenericType();
            Type list3 = TypeTest.class.getDeclaredField("list3").getGenericType();
            Type test = TypeTest.class.getDeclaredMethod("test").getGenericReturnType();
            Type testMap = TypeTest.class.getDeclaredMethod("testMap").getGenericReturnType();

            Type type1 = ParameterizedTypeUtils.get(list1, 0);
            Type type2 = ParameterizedTypeUtils.get(list2, 0);
            Type type3 = ParameterizedTypeUtils.get(list3, 0);
            Type testType = ParameterizedTypeUtils.get(test, 0);
            Type typeMapType = ParameterizedTypeUtils.get(testMap, 0);

            System.out.println(type2.getClass() + " : " + type1);
            System.out.println(type2.getClass() + " : " + type2.getTypeName());
            System.out.println(type3.getClass() + " : " + type3);
            System.out.println(testType.getClass() + " : " + testType);
            System.out.println(typeMapType.getClass() + " : " + typeMapType);
        }
    }*/
}
